<template>
  <div class="bgc_white" id="register" >
    <div  class="warranty"> 
      <el-form :model="form" :rules="rules" ref="form"  @submit.native.prevent>
        <p class="title">Lifetime Warranty</p>
        <p class="secTitleGuide">{{$t('WARRANTY.WARRANTYLOGIN')}} <span @click="goToLogIn">{{$t('DEFAULT.SIGNIN')}} ></span></p>

        <p class="secTitle">{{$t('DEFAULT.WARRANTYTITLE')}}</p>
        <p class="formTitle">{{$t('DEFAULT.EMAILADDRESS')}}</p>
        <el-form-item  prop="email">
           <el-input  v-model="form.email"  name="email" type="text" @keyup.enter.native="getEmailStatus" @blur="getEmailStatus"></el-input >
        </el-form-item>
        <p class="formTitle">{{$t('DEFAULT.STORE')}}</p>
        <el-form-item  prop="store">
          <el-select v-model="form.store" placeholder=""> 
            <el-option v-for="item in storeList"  :key="item.value" :value="item.value" :label="$t('DEFAULT.'+item.label)"></el-option>
          </el-select>
        </el-form-item>
        <p class="formTitle">{{$t('DEFAULT.PURCHASEDITEM')}}</p>
        <el-form-item  prop="purchased_item">
          <el-select v-model="form.purchased_item" placeholder=""> 
            <el-option v-for="item in purchasedList" :key="item.value" :value="item.value" :label="$t('DEFAULT.'+item.label)"></el-option>
          </el-select>
        </el-form-item>
        <p class="formTitle">{{$t('DEFAULT.FULLNAME')}}</p>
        <el-form-item  prop="truename">
          <el-input  v-model="form.truename" name="truename" type="text"></el-input >
        </el-form-item>

        <p class="formTitle">{{$t('DEFAULT.ORDERNUMBER')}} </p>
        <el-form-item  prop="order_no">
          <el-input  v-model="form.order_no" name="order_no"  type="text" readonly @focus="removeReadonly"></el-input>
        </el-form-item>

        <p class="formTitle" v-show="curEmail.sign_up == 0">{{$t('DEFAULT.PASSWORD')}} </p>
        <el-form-item  prop="password"  v-show="curEmail.sign_up == 0">
          <el-input  v-model="form.password" name="password"  :type="showPsw" >
            <i @click="isPswShow" slot="suffix" :class="showPsw == 'password' ? 'icon-nondisplay_normal iconfont': 'iconfont icon-display_normal'  "></i>
          </el-input>
        </el-form-item>
        <p class="formTitle"  v-show="curEmail.sign_up == 0">{{$t('DEFAULT.CONFIRMPSW')}} </p>
        <el-form-item  prop="confirmPwd"  v-show="curEmail.sign_up == 0">
          <el-input  v-model="form.confirmPwd" name="confirmPwd" :type="showConfirmPsw">
            <i @click="isConfirmPswShow" slot="suffix" :class="showConfirmPsw == 'password' ? 'icon-nondisplay_normal iconfont': 'iconfont icon-display_normal'  "></i>
          </el-input>
        </el-form-item>
        <p class="tip">{{$t('DEFAULT.WARRANTYFOOTER')}}</p>
        <el-button @click="submitForm()"  :loading="isRequest" :class="{'isFull': isFull}">{{$t('DEFAULT.SIGNUP')}}</el-button>
      </el-form>

     <el-dialog :close-on-click-modal="false"   :visible.sync="isInfoShow" class="warranty_dialog" :before-close="closeSignDialog">
        <div class="warranty_dialog_content" v-if="!userInfo.email" style="text-align:center">
          <p>{{$t('BETATESTER.ACCOUNTLOGIN')}}</p>
        </div>
        <div class="warranty_dialog_content" v-else style="text-align:center">
          <p>{{$t('WARRANTY.WARRANTYBENEFITSACCOUNT')}}</p>
          <p>{{$t('WARRANTY.WARRANTYBENEFITS2')}}</p>
        </div>
        <span slot="footer" class="dialog-footer">
          <router-link to="/login" v-if="!userInfo.email"><el-button type="search" >{{$t('DEFAULT.SIGNIN')}}</el-button></router-link>
           <router-link to="/my_benefits" v-else><el-button type="search" >{{$t('WARRANTY.CMP')}}</el-button></router-link>
        </span>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" :visible.sync="isGuideShow" class="warranty_dialog">
        <div class="warranty_dialog_content">
          <p>{{$t('WARRANTY.WARRANTYBENEFITSACCOUNT')}}</p>
          <p>{{$t('WARRANTY.WARRANTYRIGHTS')}}</p>
        </div>
        <span slot="footer" class="dialog-footer">
          <router-link :to="{path:'/warranty_active',query:{email: form.email}}"><el-button type="search" class="btnWidth" >Subscribe Warranty</el-button></router-link>
        </span>
      </el-dialog>
    </div>
  </div>

 
</template>

<script>
import { mapGetters } from 'vuex'
import { warranty } from '@/api/register.js'
import { allEmailGet } from '@/api/contactUs'
import { timeFormat } from '@/utils/index.js'
export default {
  data () {
    const validatePsw = (rule, value, callback) => {
      if (value === '' || value.length < 6 || value.length > 12) {
        callback(new Error(this.$t('DEFAULT.MSGPWSLEN')));
      } else if (this.form.password && this.form.confirmPwd && this.form.password  !== this.form.confirmPwd) {
        callback(new Error(this.$t('DEFAULT.MSGOSWDIFF')))
      } else {
        callback()
      }
    };
    return {
      isGuideShow: false,
      isInfoShow: false,
      isRequest:  false,
      showPsw: 'password',
      showConfirmPsw: 'password',
      emailList: [],
      curEmail: {
        sign_up: 1
      },
      form:{
        store: '',
        purchased_item: '',
        email: '',
        order_no: '',
        truename: '',
        password: '',
        confirmPwd: ''
      },
      storeList: [
        {value:'amazon.com (US)', label: 'STOREUS'},
        {value:'amazon.ca', label: 'STORECA'},
        {value:'amazon.de', label: 'STOREDE'},
        {value:'amazon.fr', label: 'STOREFR'},
        {value:'amazon.it', label: 'STOREIT'},
        {value:'amazon.co.jp', label: 'STOREJP'},
        {value:'amazon.es', label: 'STOREES'},
        {value:'amazon.co.uk', label: 'STOREUK'},
        {value:'amazon.com.au', label: 'STOREAU'},
        // {value:'AliExpress', label: 'STOREALIEXPRESS'},
        // {value:'eBay', label: 'STOREEBAY'},
        
      ],
      purchasedList:[
        {value:'Cable', label: 'PICABLE'},
        {value:'Charger', label: 'PICHARGER'},
        {value:'Adapter', label: 'PIADAPTER'},
        {value:'Stand', label: 'PISTAND'},
      ],
      rules: {
        store: [
          { required: true, trigger: 'change' }
        ],
        purchased_item: [
          { required: true, message: 'Purchased Item is required' , trigger: 'change' }
        ], 
        email: [
          { required: true, message:  this.$t('CONTACTUS.ENTEREMAILADDRESS'), trigger: 'blur' },
          { type: 'email', message: this.$t('DEFAULT.CORRECTEMAIL'), trigger: 'blur' }
        ],
        order_no: [
          { required: true, message: this.$t('CONTACTUS.ENTERAMAZONORDERID'), trigger: 'blur' }
        ],
        truename: [ 
          { required: true, message: 'Full Name is required', trigger: 'blur' }
        ],
        password: [
          { required: true,trigger: 'blur' , validator: validatePsw},
          { min: 6, max: 12, message: this.$t('DEFAULT.MSGPWSLEN'), trigger: 'blur' }
        ],
        confirmPwd: [
          { required: true, trigger: 'blur' , validator: validatePsw},
          { min: 6, max: 12,  trigger: 'blur' }
        ]
      
      }
    }
  },
  computed:{
    ...mapGetters(['userInfo', 'curSite']),
    isFull () {
      let isFull = true
      let store =  this.form.store.length > 0
      let purchased_item = this.form.purchased_item.length > 0
      let email = this.form.email.length > 0
      let order_no = this.form.order_no.length > 0
      let truename = this.form.truename.length > 0
    
      
      if (store && purchased_item && email && order_no && truename){
        let array = ['store', 'purchased_item', 'email', 'order_no','truename']
        if(this.curEmail.sign_up == 0){
          array.push('password')
          array.push('confirmPwd')  
        }
        this.$refs.form.validateField(array, (msg)=>{
          isFull = isFull && !msg
        })
      } else {
        isFull = false
      }
      return isFull
    },
    
  },
  watch:{
    userInfo(){
      this.setFormData()
    }
  },
  mounted (){
    this.setFormData()
  },
  methods: {
    closeSignDialog () {
      this.isInfoShow = !this.isInfoShow
    },
    setFormData(){
      if(this.userInfo.store){
        this.form.store = this.userInfo.store
      } 
      if(this.userInfo.purchased_item){
        this.form.purchased_item = this.userInfo.purchased_item
      } 
      if(this.userInfo.email){
        this.form.email = this.userInfo.email
      } 
      if(this.userInfo.order_no){
        this.form.order_no = this.userInfo.order_no
      }
      if(this.userInfo.truename){
        this.form.truename = this.userInfo.truename
      }  
    },
    removeReadonly(event){
      event.target.removeAttribute('readonly')
    },
    getEmailStatus (event) {
      event.target.blur();
      this.$refs.form.validateField('email', (msg)=>{
        if(!msg){
          this.getEmail()
        }
      })
    },
    getEmail(){
      let params = {
        email:this.form.email
      }
      allEmailGet(params).then(res=>{
        this.curEmail = res.data
        if(res.data.sign_up == 1 ){
          this.isInfoShow = true
        }
      })
    },
    sendEmail () {
      let url = 'mailto:support@bonoch.com?subject=&body='
      console.log(url)
      window.open(url)
    },
    changeEmail (value) {
      let emailList = this.emailList
      for (let i = 0; i < emailList.length; i++ ){
        if (emailList[i].value == value){
          this.curEmail = emailList[i]
        }
      }
      this.form.password = ''
      this.form.confirmPwd = ''
    },

    isPswShow () {
      if(this.showPsw == 'password'){
        this.showPsw = 'text'
      } else {
        this.showPsw = 'password'
      }
    },
    isConfirmPswShow () {
      if(this.showConfirmPsw == 'password'){
        this.showConfirmPsw = 'text'
      } else {
        this.showConfirmPsw = 'password'
      }
    },
    submitForm() {
      let isFull = true
      let array = ['store', 'purchased_item', 'email', 'order_no','truename']
      if(this.curEmail.sign_up == 0){
        array.push('password')
        array.push('confirmPwd')  
      }
      this.$refs.form.validateField(array, (msg)=>{
        isFull = isFull && !msg
        this.isFull = isFull
      })
      if(isFull){
          this.signUp()
        }
    },
      goToLogIn () {
      this.$router.push('/login')
    },
    signUp(){
      this.isRequest = true
      let params = this.form
      params.language = this.curSite.site
      params.local_time = timeFormat(new Date()).split(' ')[0],
      warranty(params).then(res=>{
        if(res.state == 1 ){
          let data =res.data
          if(data.w_status == 1){ // 订阅
            this.isInfoShow = true
          } else if (data.w_status == 2){// 取消订阅
            this.isGuideShow = true
          } else { // warranty 为空 
            if(data.email_is_valid ==1){//邮箱有效
              if(data.b_status == 0){
                this.$router.push('/betatester_guide')
              }else if(data.b_status == 2){
                this.$router.push('/betatester_active_guide')
              }else if(data.b_status == 1){
                this.$router.push('/warranty_success')
              }
            }else if(data.email_is_valid ==2){//邮箱无效
              this.$router.push('/register_email')
            }

          }
        }
        this.$store.dispatch('GetUserInfo')
        this.isRequest = false
      })
    },
   
  }
}
</script>

<style lang="scss">
@import '@/styles/register/register.scss';
#register {
  .warranty{
    .title{
      margin-bottom: 16px;
    }
    .secTitleGuide{
      color: #666;
      font-size: 14px;
      margin-bottom: 16px;
      text-align: center;
      >span{
        margin-left: 40px;
        cursor: pointer;
        color: #0B95FD;
      }
    }

  }
}
#register {
  @include respond('768'){
    .warranty{
      .secTitleGuide{
        white-space: nowrap;
        text-align: left;
         > span{
          margin-left: 0px;
          display: block;
        } 
      }
    }
  }
}

</style>